# -*- coding: utf-8 -*-
#coding=utf-8

import web
import os
import config
from action.admin.base import adminAction
from model.image import image
from model.ad import ad
from model.album import album
from model.category import category

'''
Admin controller: producing advertisement administration views.
'''
class refererAction(adminAction):
    def __init__(self, name = '广告管理'):
        adminAction.__init__(self, name)


    def GET(self, name):
        if name == 'list':
            return self.list()
        elif name == 'delete':
            return self.delete()
        elif name == 'add':
            return self.add()
        elif name == 'edit':
            return self.edit()
        else:
            return self.notFound()

    def POST(self, name):
        if name == 'save':
            return self.save()
        elif name == 'deleteBatch':
            return self.deleteBatch()  
        elif name == 'modify':
            return self.modify()
        else:
            return self.notFound()

    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        adObj = ad()
        listData = adObj.getOne('COUNT(*) AS `total`', condition)
        totalCount = listData['total']
        adList = adObj.getList('*', condition, '', str(offset) + ',' + str(count))
        pageString = self.getPageStr(self.makeUrl('/admin/ad/list'), page, count, totalCount)
        self.privData['AD_LIST'] = adList
        self.privData['PAGE_STRING'] = pageString
        self.privData['ALBUM_LIST'] = {}
        self.privData['CATEGORY_LIST'] = {}

        albumList = album().getList('*', condition)
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        categoryList = category().getList('*', condition)
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        return self.display('adList')

    def delete(self):
        inputParams = self.getInput()

        try:
            condition = { 'id': int(inputParams['id']) }
            ad().delete(condition)
        except Exception, e:
            return self.error(msg = '广告删除失败: %s' % e, url=self.makeUrl('/admin/ad/list'))
    
        return self.success(msg='广告删除成功', url=self.makeUrl('/admin/ad/list'))

    def deleteBatch(self):
        inputParams = self.getInput()
        try:
            condition = ' id IN (' + inputParams['delitems'] +')'
            ad().delete(condition)
        except Exception, e:
            return self.error(msg='广告删除失败: %s' % e, url=self.makeUrl('/admin/ad/list'))

        return self.success(msg='广告删除成功', url=self.makeUrl('/admin/ad/list'))
        
    def add(self):
        condition = {}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc']

        condition = 'id > 1'
        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = 1
        self.privData['SUBMIT_NAME'] = "thumbnail"
        self.privData['CATEGORY_LIST'] = {}

        categoryList = category().getList('*', condition)
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        return self.display('adAdd')
    
    def modify(self):
        inputParams= self.getInput()

        try:
            data={
                'category':     int(inputParams['category']),
                'album':        int(inputParams['album']),
            }
            ad().update(data, {'id': int(inputParams['id'])})
        except Exception, e:
            return self.error(msg = '广告修改失败: %s' % e, url=self.makeUrl('/admin/ad/list'))

        return self.success('广告修改成功', url=self.makeUrl('/admin/ad/list'))

    def edit(self):
        inputParams = self.getInput()

        adObj = ad().getOne('*', {'id': int(inputParams['id'])})
        if not adObj:
            return self.error(msg = '广告不存在', url=self.makeUrl('/admin/ad/list'))

        self.privData['AD_ID'] =   adObj['id']
        self.privData['AD_CATEGORY'] =   adObj['category']
        self.privData['AD_ALBUM'] =   adObj['album']

        condition = {}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc']

        condition = 'id > 1'
        self.privData['CURRENT_ALBUM'] = adObj['album']
        self.privData['CATEGORY_LIST'] = {}

        categoryList = category().getList('*', condition)
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        return self.display('adEdit')


    def save(self):
        inputParams= self.getInput()  
        try:
            data = {
                'category':     int(inputParams['category']),
                'album':        int(inputParams['album']),
            }
            ad().insert(data)
        except Exception, e:
            return self.error(msg = '广告保存失败: %s' % e, url=self.makeUrl('/admin/ad/list'))
        return self.success('广告保存成功', url=self.makeUrl('/admin/ad/list'))
